package fr.web325.servlet.client.cart;

import fr.web325.bean.Book;
import fr.web325.bean.Order;
import fr.web325.bean.User;
import fr.web325.dao.ClientDao;
import fr.web325.utils.CodeUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.*;


@WebServlet("/shop/client/accounts")
public class Accounts extends HttpServlet {
    // 生成订单
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取购物车对象
        HttpSession session = req.getSession();
        Map<Book,Integer> cart = (Map<Book, Integer>) session.getAttribute("cart");
        // 生成订单对象
        Order order = new Order();
        // 判断是否登录
        if(session.getAttribute("user") == null || cart==null){
            resp.getWriter().append("请先进行登录!");
            return;
        }
        // 获取用户对象
        User user = (User) session.getAttribute("user");
        ClientDao service = new ClientDao();
        // 总价
        double totalPrice = 0;
        // 商品ID列表
        HashMap<String, Integer > list = new HashMap<String, Integer>();
        try {
            BeanUtils.populate( order,req.getParameterMap());
            //  总价 时间 用户ID
            for (Map.Entry<Book, Integer> entry : cart.entrySet()) {
                totalPrice += (entry.getKey().getPrice()) * entry.getValue();
                list.put (entry.getKey().getId(),entry.getValue());
            }
            String order_id = new CodeUtils().getId();
            order.setId(order_id);
            order.setOrderTime(new Date());
            order.setMoney(totalPrice);
            order.setUser_id(user.getId());
            // 插入到 order表
            try {
                if(service.addOrder(order)){
                    // 插入成功 再插入到orderitem表中
                    service.addOrderItem(order_id,list);
                    // 清空购物车 跳转pay 确认支付
                    session.removeAttribute("cart");
                    req.setAttribute("orderId",order_id);
                    req.getRequestDispatcher("/shop/client/pay").forward(req,resp);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
